<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="备件编号" prop="partNo">
        <el-input
          v-model="queryParams.partNo"
          placeholder="请输入备件编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="执行者" prop="operator">
        <el-input
          v-model="queryParams.operator"
          placeholder="请输入执行者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出入库类型" prop="operationType">
        <el-select
          v-model="queryParams.operationType"
          placeholder="请选择出入库类型"
          clearable
        >
          <el-option label="全部" value="" />
          <el-option label="入库" value="IN" />
          <el-option label="出库" value="OUT" />
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间" prop="operationTime">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="operation-buttons" style="margin-bottom: 20px;">
      <!-- 左侧：搜索操作按钮 -->
      <div class="search-buttons" style="display: inline-block; margin-right: 20px;">
        <el-button type="primary" size="small" @click="handleQuery" style="margin-right: 8px;">
          <i class="el-icon-search"></i> 搜索
        </el-button>
        <el-button size="small" @click="resetQuery" style="margin-right: 8px;">
          <i class="el-icon-refresh"></i> 重置
        </el-button>
        <el-button type="text" size="small" @click="toggleSearch">
          <i class="el-icon-arrow-down" v-if="!showSearch"></i>
          <i class="el-icon-arrow-up" v-else></i>
          {{ showSearch ? '收起' : '展开' }}
        </el-button>
      </div>
      
      <!-- 右侧：功能操作按钮 -->
      <div class="action-buttons" style="display: inline-block;">
        <el-button
          size="small"
          icon="el-icon-arrow-left"
          @click="handleBackToPart"
          style="margin-right: 8px;"
        >返回</el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          size="small"
          @click="handleExport"
          v-hasPermi="['system:item:export']"
        >导出</el-button>
      </div>
    </div>

    <!-- 出入库明细表格 -->
    <el-table v-loading="loading" :data="itemList">
      <el-table-column label="备件编号" align="center" prop="partNo" width="120" />
      <el-table-column label="备件名称" align="center" prop="partName" min-width="150" />
      <el-table-column label="出入库类型" align="center" prop="operationType" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.operationType === 'IN' ? 'success' : 'danger'">
            {{ scope.row.operationType === 'IN' ? '入库' : '出库' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="入库数量" align="center" prop="inQuantity" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.operationType === 'IN'">{{ scope.row.quantity }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="出库数量" align="center" prop="outQuantity" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.operationType === 'OUT'">{{ scope.row.quantity }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="执行者" align="center" prop="operator" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.operatorName || scope.row.operator || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="仓库" align="center" prop="warehouseCode" width="140">
        <template slot-scope="scope">
          <span>{{ scope.row.warehouseName || getWarehouseName(scope.row.warehouseCode) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作时间" align="center" prop="operationTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operationTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" min-width="200" />
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listTransaction, getTransaction } from '@/api/inventory/transaction'

export default {
  name: "Item",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出入库明细表格数据
      itemList: [],
      // 仓库选项
      warehouseOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        partNo: null,
        operator: null,
        operationType: null,
        operationTime: null
      }
    }
  },
  async created() {
    // 从路由参数获取备件编号
    if (this.$route.query.partNo) {
      this.queryParams.partNo = this.$route.query.partNo
    }
    await this.loadWarehouses()
    await this.getList()
  },
  methods: {
    // 加载仓库列表
    loadWarehouses() {
      return import('@/api/inventory/warehouse').then(mod => {
        const listFn = mod.listWarehouseDTO || mod.listWarehouse || mod.list
        if (!listFn) return
        return listFn({ pageNum: 1, pageSize: 9999 }).then(res => {
          const rows = res.rows || res.data || []
          this.warehouseOptions = rows.map(w => ({
            code: w.warehouseCode || w.code || w.id,
            name: w.warehouseName || w.name || w.label
          }))
        })
      }).catch(() => { this.warehouseOptions = [] })
    },
    getWarehouseName(code) {
      if (!code) return ''
      const w = this.warehouseOptions.find(x => String(x.code) === String(code))
      return w ? w.name : code
    },
    /** 查询出入库明细列表 */
    getList() {
      this.loading = true
      const params = { pageNum: 1, pageSize: 50 } // 拉较多记录在前端汇总
      listTransaction(params).then(async res => {
        const rows = res.rows || []
        // 从列表结果中构建 txNo -> operatorName 映射（后端DTO已left join用户表）
        const txNoToOperatorName = new Map()
        rows.forEach(r => {
          const k = r.txNo || r.tx_no
          const v = r.operatorName || r.operator_name || ''
          if (k) txNoToOperatorName.set(k, v)
        })
        const detailPromises = rows.map(r => getTransaction(r.txNo || r.tx_no))
        const detailResponses = await Promise.all(detailPromises)
        const allItems = []
        detailResponses.forEach(dr => {
          const items = (dr.data && (dr.data.transactionItems || dr.data.items)) || []
          items.forEach(it => {
            allItems.push({
              txNo: it.txNo || (dr.data && (dr.data.txNo || dr.data.tx_no)) || '',
              partNo: it.partNo,
              partName: it.partName || '',
              operationType: (it.direction === 'IN' || it.direction === 'INBOUND' || it.direction === 'IN') ? 'IN' : 'OUT',
              quantity: it.quantity,
              operator: dr.data && (dr.data.operatorName || dr.data.operatorId || ''),
              operatorName: (dr.data && (dr.data.operatorName || dr.data.operator_name)) || txNoToOperatorName.get((dr.data && (dr.data.txNo || dr.data.tx_no)) || '') || '',
              warehouseCode: dr.data && (dr.data.warehouseCode || dr.data.warehouse_code || ''),
              warehouseName: this.getWarehouseName(dr.data && (dr.data.warehouseCode || dr.data.warehouse_code || '')),
              operationTime: dr.data && (dr.data.createdAt || dr.data.createTime || ''),
              remark: it.remark || (dr.data && dr.data.remark) || ''
            })
          })
        })

        // 应用筛选
        let filteredList = allItems
        if (this.queryParams.partNo) {
          const kw = this.queryParams.partNo.toString().toLowerCase()
          filteredList = filteredList.filter(x => (x.partNo || '').toLowerCase().includes(kw))
        }
        if (this.queryParams.operator) {
          const kw = this.queryParams.operator.toString().toLowerCase()
          filteredList = filteredList.filter(x => ((x.operatorName || x.operator || '') + '').toLowerCase().includes(kw))
        }
        if (this.queryParams.operationType) {
          filteredList = filteredList.filter(x => x.operationType === this.queryParams.operationType)
        }

        // 时间范围
        if (this.dateRange && this.dateRange.length === 2) {
          const [start, end] = this.dateRange
          const st = new Date(start + ' 00:00:00').getTime()
          const et = new Date(end + ' 23:59:59').getTime()
          filteredList = filteredList.filter(x => {
            const t = new Date(x.operationTime).getTime()
            return t >= st && t <= et
          })
        }

        // 按时间倒序
        filteredList.sort((a, b) => new Date(b.operationTime) - new Date(a.operationTime))
        this.total = filteredList.length
        this.itemList = filteredList
      }).finally(() => {
        this.loading = false
      })
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    
    /** 切换搜索显示 */
    toggleSearch() {
      this.showSearch = !this.showSearch
    },
    
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/item/export', {
        ...this.queryParams
      }, `item_${new Date().getTime()}.xlsx`)
    },
    /** 返回备件台账 */
    handleBackToPart() {
      const q = this.queryParams.partNo ? { partNo: this.queryParams.partNo } : {}
      this.$router.push({ path: '/system/part/index', query: q })
    }
  }
}
</script>

<style scoped>
.operation-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.search-buttons {
  display: flex;
  align-items: center;
}

.action-buttons {
  display: flex;
  align-items: center;
}

/* 统一按钮样式 */
.operation-buttons .el-button {
  border-radius: 4px;
  font-weight: 500;
}

.operation-buttons .el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
}

.operation-buttons .el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.operation-buttons .el-button--text {
  color: #409EFF;
  padding: 8px 12px;
}

.operation-buttons .el-button--text:hover {
  color: #66b1ff;
}
</style>